package com.th.therp.service.Impl;

import com.th.therp.exception.BaseException;
import com.th.therp.mapper.MaterialCategoryMapper;
import com.th.therp.pojo.emtity.MaterialCategory;
import com.th.therp.service.MaterialCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MaterialCategoryServiceImpl implements MaterialCategoryService {

    @Autowired
    private MaterialCategoryMapper materialCategoryMapper;

    @Override
    public List<MaterialCategory> list() {
        return materialCategoryMapper.list();
    }

    @Override
    public void add(MaterialCategory materialCategory) {
        MaterialCategory existingMaterialCategory = materialCategoryMapper.findByName(materialCategory.getName());
        if (existingMaterialCategory == null) {
            materialCategoryMapper.add(materialCategory);
        }else {
            throw new BaseException("该分类已存在");
        }
    }

    @Override
    public void update(MaterialCategory materialCategory) {
        MaterialCategory existingMaterialCategory = materialCategoryMapper.findByName(materialCategory.getName());
        if (existingMaterialCategory != null && !existingMaterialCategory.getId().equals(materialCategory.getId())) {
            throw new BaseException("该分类已存在");
        }else {
            materialCategoryMapper.update(materialCategory);
        }
    }

    @Override
    public void delete(List<Integer> ids) {
        ids.forEach(id -> {
            MaterialCategory materialCategory = MaterialCategory.builder()
                    .id(id)
                    .isDeleted(1)
                    .build();
           materialCategoryMapper.update(materialCategory);
        });
    }

    @Override
    public String findCategoryNameById(Integer categoryId) {
        return materialCategoryMapper.findCategoryNameById(categoryId);
    }
}